import * as fs from 'fs';
import * as path from 'path';


export  const existsSync = function (dirPath) {
    return new Promise((resolve, reject) => {
      // 异步检查目录是否存在
      fs.access(dirPath, fs.constants.F_OK, (err) => {
        if (err) {
          // 目录不存在，创建目录
          fs.mkdir(dirPath, { recursive: true }, (mkdirErr) => {
            if (mkdirErr) {
              reject(mkdirErr);
              console.error(mkdirErr);
            } else {
              resolve(true);
              console.log('目录创建成功');
            }
          });
        } else {
          resolve(false);
          console.log('目录已存在');
        }
      });
    });
  };
  
  export const writerStream = function(fileName, data){
  
    return new Promise((resolve, reject) => {
  
  
      fs.writeFile(fileName, data, (err) => {
        if (err) {
          console.log(err);
          reject(err);
        } else {
          console.log('写入成功');
          resolve(true);
        }
      });
  
     
    })
  }


  export  function deleteFolderRecursive(folderPath) {
    //判断文件夹是否存在
    if (fs.existsSync(folderPath)) {
      //读取文件夹下的文件目录，以数组形式输出
      fs.readdirSync(folderPath).forEach((file) => {
        //拼接路径
        const curPath = path.join(folderPath, file);
        //判断是不是文件夹，如果是，继续递归
        if (fs.lstatSync(curPath).isDirectory()) {
          deleteFolderRecursive(curPath);
        } else {
          //删除文件或文件夹
          fs.unlinkSync(curPath);
        }
      });
      //仅可用于删除空目录
      fs.rmdirSync(folderPath);
    }
  }
 export function emptyDirectory(dir) {
  fs.readdir(dir, (err, files) => {
    if (err) throw err;
    files.forEach(file => {
      const fullPath = path.join(dir, file);
      fs.unlink(fullPath, err => {
        if (err) throw err;
      });
    });
  });
}
 
